<template>
    <el-row class="contain-box">
        <site-nav/>
        <div class="view-body">
            <el-row>
                <el-form class="inline-form" inline>
                    <el-form-item>
                        <el-button @click="addDepartment" type="primary"><i class="el-icon-plus el-icon--left"/>添加部门
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <el-table :data="tree" border ref="table" row-key="departmentId" size="small">
                    <el-table-column fixed label="部门ID" prop="departmentId"/>
                    <el-table-column align="center" fixed label="部门名称" prop="departmentName"/>
                    <el-table-column align="center" label="主管领导" prop="directorUserName" width="100"/>
                    <el-table-column align="center" label="分管领导" prop="chargeUserName" width="100"/>
                    <el-table-column align="center" label="部门类型" width="200">
                        <template slot-scope="scope">
                            <span v-if="scope.row.departmentTypeKey">{{scope.row.departmentTypeName}}</span>
                            <br>
                            <span v-if="scope.row.departmentTypeKey">({{scope.row.departmentTypeKey}})</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="排序" prop="orderNum" width="50"/>
                    <el-table-column label="操作" width="420">
                        <template slot-scope="scope">
                            <el-button @click.stop="toPermissionPage(scope.row)" size="mini" type="primary">权限设置
                            </el-button>
                            <el-button @click.stop="addDepartment(scope.row)" size="mini" type="primary">添加下级
                            </el-button>
                            <el-button @click.stop="updateDepartment(scope.row)" size="mini" type="primary"
                                       v-if="scope.row.departmentId !== 0">修改
                            </el-button>
                            <el-button :disabled="scope.row.children && scope.row.children.length > 0"
                                       @click.stop="deleteDepartment(scope.row)" size="mini"
                                       type="danger"
                                       v-if="scope.row.departmentId !== 0">删除
                            </el-button>
                            <el-dropdown class="dropdown" v-if="scope.row.departmentId !== 0">
                                <el-button size="mini" type="primary">
                                    操作<i class="el-icon-arrow-down el-icon--right"/>
                                </el-button>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item @click.native="updateDirectorUser(scope.row)">设置主管领导
                                    </el-dropdown-item>
                                    <el-dropdown-item @click.native="updateChargeUser(scope.row)">设置分管领导
                                    </el-dropdown-item>
                                    <el-dropdown-item @click.native="distribution(scope.row)" divided>职位分配
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
            <el-dialog :before-close="dialogClose" :title="dialog.isAdd ? '新增部门' : '修改部门'" :visible.sync="dialog.show"
                       class="dialog">
                <el-form :model="info" :rules="rules" label-width="120px" ref="form" size="small">
                    <el-form-item label="上级部门" prop="parentId" required>
                        <dept-tree-selecter :filter="deptDialogFilter" :show-empty="true" ref="deptSelecter"
                                            v-model="info.parentId"/>
                    </el-form-item>
                    <el-form-item label="部门名称" prop="departmentName" required>
                        <el-input type="text" v-model="info.departmentName" maxlength="100"/>
                    </el-form-item>
                    <el-form-item label="部门类型">
                        <el-select placeholder="请选择" v-model="info.departmentTypeKey">
                            <el-option label="无" value=""/>
                            <el-option :key="item.departmentTypeKey" :label="item.departmentTypeName"
                                       :value="item.departmentTypeKey" v-for="item in departmentTypes"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input type="number" v-model="info.orderNum"/>
                    </el-form-item>
                    <el-form-item label="说明">
                        <el-input :rows="4" type="textarea" v-model="info.remark"/>
                    </el-form-item>
                </el-form>
                <div class="dialog-footer" slot="footer">
                    <el-button @click="dialogClose" size="mini">取 消</el-button>
                    <el-button :loading="dialog.submitting" @click="dialogSubmit" size="mini" type="primary">确 定
                    </el-button>
                </div>
            </el-dialog>

            <el-dialog :before-close="dialog2Close" :visible.sync="dialog2.show" class="dialog" title="设置主管领导">
                <el-form label-width="120px" size="small">
                    <el-form-item label="主管领导">
                        <el-select :loading="dialog2.loading" :remote-method="dialog2Search" class="user-selecter"
                                   clearable filterable placeholder="请选择"
                                   remote v-model="dialog2.userId">
                            <el-option label="无" value="0"/>
                            <el-option :key="user.userId" :label="user.name + '(' + user.departmentName + ')'"
                                       :value="user.userId" class="user-selecter-item"
                                       v-for="user in dialog2.users">
                                <user-select-item :value="user"/>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div class="dialog-footer" slot="footer">
                    <el-button @click="dialog2Close" size="mini">取 消</el-button>
                    <el-button :loading="dialog2.submitting" @click="dialog2Submit" size="mini" type="primary">确 定
                    </el-button>
                </div>
            </el-dialog>

            <el-dialog :before-close="dialog3Close" :visible.sync="dialog3.show" class="dialog" title="设置分管领导">
                <el-form label-width="120px" size="small">
                    <el-form-item label="分管领导">
                        <el-select :loading="dialog3.loading" :remote-method="dialog3Search" class="user-selecter"
                                   clearable filterable placeholder="请选择"
                                   remote v-model="dialog3.userId">
                            <el-option label="无" value="0"/>
                            <el-option :key="user.userId" :label="user.name + '(' + user.departmentName + ')'"
                                       :value="user.userId" class="user-selecter-item"
                                       v-for="user in dialog3.users">
                                <user-select-item :value="user"/>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div class="dialog-footer" slot="footer">
                    <el-button @click="dialog3Close" size="mini">取 消</el-button>
                    <el-button :loading="dialog3.submitting" @click="dialog3Submit" size="mini" type="primary">确 定
                    </el-button>
                </div>
            </el-dialog>
        </div>
    </el-row>
</template>
<script lang="ts">
  import {ID} from '@/api/http';
  import DepartmentApi from '@/api/user/departmentApi';
  import DepartmentTypeApi from '@/api/user/departmentTypeApi';
  import UserApi from '@/api/user/userApi';
  import DeptTreeSelecter from '@/components/department/DeptTreeSelecter.vue';
  import Department, {ALL_DEPARTMENT} from '@/structure/department';
  import DepartmentType from '@/structure/departmentType';
  import DepartmentUser from '@/structure/departmentUser';
  import DialogInfo from '@/structure/dialogInfo';
  import FormRules from '@/structure/formRules';
  import User from '@/structure/user';
  import {ElForm} from 'element-ui/types/form';
  import {Component, Vue} from 'vue-property-decorator';

  @Component
  export default class Page extends Vue {
    public tree: Department[] = [];
    public departmentTypes: DepartmentType[] = [];
    public dialog: DialogInfo = new DialogInfo();
    public dialog2: { [key: string]: any } = Object.assign(new DialogInfo(), {
      departmentId: null as ID,
      userId: null as ID,
      users: [] as User[]
    });
    public dialog3: { [key: string]: any } = Object.assign(new DialogInfo(), {
      departmentId: null as ID,
      userId: null as ID,
      users: [] as User[]
    });
    public info: Department = new Department();
    public rules: FormRules = {
      parentId: [
        {
          required: true,
          message: '请选择上级部门'
        }
      ],
      departmentName: [
        {
          required: true,
          message: '请输入部门名称'
        }
      ]
    };

    public get form(): ElForm {
      return this.$refs.form as ElForm;
    }

    public created(): void {
      this.getDataList();
      DepartmentTypeApi.all().then((res) => {
        this.departmentTypes = res;
      });
    }

    public deptDialogFilter(item: Department): boolean {
      if (this.dialog.isAdd) {
        return false;
      }

      return item.departmentId === this.info.departmentId;
    }

    public getDataList(): void {
      if (this.$refs.table) {
        this.$contractTree(this.$refs.table);
      }

      DepartmentApi.tree().then((res) => {
        const deptSelecter = this.$refs.deptSelecter as DeptTreeSelecter;
        if (deptSelecter) {
          deptSelecter.refreshByData(res);
        }
        this.tree = [ALL_DEPARTMENT].concat(res);

        this.$nextTick(() => {
          this.$expandTree(this.$refs.table);
        });
      });
    }

    public addDepartment(info: Department): void {
      this.info = new Department();
      this.info.parentId = info && info.departmentId ? info.departmentId : '0';

      this.dialog.isAdd = true;
      this.dialog.show = true;

      this.$nextTick(() => {
        this.form.clearValidate();
      });
    }

    public updateDepartment(info: Department): void {
      this.info = {...info};

      this.dialog.isAdd = false;
      this.dialog.show = true;

      this.$nextTick(() => {
        this.form.clearValidate();
      });
    }

    public deleteDepartment(info: Department): void {
      this.$confirm('是否删除该部门?', '删除部门', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DepartmentApi.delete(info.departmentId).then(() => {
          this.getDataList();
          this.$message.success('删除成功!');
        });
      });
    }

    public dialogClose(): void {
      this.info = new Department();
      this.dialog.show = false;
      this.form.clearValidate();
    }

    public dialogSubmit(): void {
      if (this.dialog.submitting) {
        return;
      }

      this.form.validate((valid) => {
        if (!valid) {
          return;
        }

        this.dialog.submitting = true;

        const func = this.dialog.isAdd ? DepartmentApi.save : DepartmentApi.update;
        const msg = this.dialog.isAdd ? '添加部门成功' : '编辑部门成功';

        func.call(DepartmentApi, this.info).then(() => {
          this.getDataList();
          this.dialogClose();
          this.dialog.submitting = false;
          this.$message.success(msg);
        }).catch(() => {
          this.dialog.submitting = false;
        });
      });
    }

    public distribution(info: Department): void {
      this.$router.push({
        name: 'User_Department_Distribution',
        params: {
          departmentId: '' + info.departmentId
        },
        query: {
          departmentName: info.departmentName
        }
      });
    }

    public toUserPage(info: Department): void {
      this.$router.push({
        name: 'User_User',
        query: {
          departmentId: '' + info.departmentId
        }
      });
    }

    public toPermissionPage(info: Department): void {
      this.$router.push({
        name: 'User_Department_Permission',
        params: {
          departmentId: '' + info.departmentId
        }
      });
    }

    // 设置主管领导
    public updateDirectorUser(info: Department): void {
      this.dialog2.show = true;
      this.dialog2.departmentId = info.departmentId;
      this.dialog2.userId = info.directorUserId || null;
      this.dialog2Search();
    }

    public dialog2Close(): void {
      this.dialog2.show = false;
      this.dialog2.submitting = false;
      this.dialog2.departmentId = null;
      this.dialog2.userId = null;
      this.dialog2.users = [];
    }

    public dialog2Submit(): void {
      if (this.dialog2.submitting) {
        return;
      }

      this.dialog2.submitting = true;

      const userId = this.dialog2.userId;

      if (userId > 0) {
        DepartmentApi.setDirectorUser({
          departmentId: this.dialog2.departmentId,
          userId
        } as DepartmentUser).then(() => {
          this.$message.success('设置主管领导成功');
          this.getDataList();
          this.dialog2Close();
        });
      } else {
        DepartmentApi.removeDirectorUser(this.dialog2.departmentId).then(() => {
          this.$message.success('设置主管领导成功');
          this.getDataList();
          this.dialog2Close();
        });
      }
    }

    public dialog2Search(key?: string): void {
      if (this.dialog2.loading) {
        return;
      }

      this.dialog2.loading = true;

      UserApi.all({nameLike: key}).then((res) => {
        this.dialog2.users = res;
        this.dialog2.loading = false;
      });
    }

    // 设置分管领导
    public updateChargeUser(info: Department): void {
      this.dialog3.show = true;
      this.dialog3.departmentId = info.departmentId;
      this.dialog3.userId = info.chargeUserId || null;
      this.dialog3Search();
    }

    public dialog3Close(): void {
      this.dialog3.show = false;
      this.dialog3.submitting = false;
      this.dialog3.departmentId = null;
      this.dialog3.userId = null;
      this.dialog3.users = [];
    }

    public dialog3Submit(): void {
      if (this.dialog3.submitting) {
        return;
      }

      this.dialog3.submitting = true;

      const userId = this.dialog3.userId;

      if (userId > 0) {
        DepartmentApi.setChargeUser({
          departmentId: this.dialog3.departmentId,
          userId
        } as DepartmentUser).then(() => {
          this.$message.success('设置分管领导成功');
          this.getDataList();
          this.dialog3Close();
        });
      } else {
        DepartmentApi.removeChargeUser(this.dialog3.departmentId).then(() => {
          this.$message.success('设置分管领导成功');
          this.getDataList();
          this.dialog3Close();
        });
      }
    }

    public dialog3Search(key?: string): void {
      if (this.dialog3.loading) {
        return;
      }

      this.dialog3.loading = true;

      UserApi.all({nameLike: key}).then((res) => {
        this.dialog3.users = res;
        this.dialog3.loading = false;
      });
    }
  }
</script>
<style lang="scss" scoped>
    .blank-line {
        margin-top: 10px;
    }

    .dropdown {
        margin-left: 10px;
    }
</style>
